package com.sap.sap_mangers.service.Impl;

import com.alibaba.fastjson.JSON;
import com.sap.sap_mangers.domain.LoginUser;
import com.sap.sap_mangers.mapper.MenuMapper;
import com.sap.sap_mangers.mapper.UserMapper;
import com.sap.sap_mangers.pojo.User;
import com.sap.sap_mangers.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 阿东
 * @date 2022/7/5 [1:30]
 */
@Service
public class UserDetailImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<String> list;
        //1.根据用户名去数据库查询，如果不存在抛出异常
        Map<String, String> user = cacheService.getUser();
        String userJson = user.get(username);
        if (userJson == null) {
            User userByUserName = userMapper.getUserByUserName(username);
            if (Objects.isNull(userByUserName)) {
                throw new UsernameNotFoundException("用户名不存在");
            }
            cacheService.updateUser(username);
            list = menuMapper.selectPermsByUserId(userByUserName.getUsername());
            return new LoginUser(userByUserName, list);
        }
        User userObject = JSON.parseObject(userJson, User.class);
        if (userObject != null) {
            //把数据封装成对象
            list = menuMapper.selectPermsByUserId(userObject.getUsername());
            System.out.println(list);
            return new LoginUser(userObject, list);
        }
        return new LoginUser(null, null);
    }
}
